package com.breeze.skinlib

import android.content.res.ColorStateList
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.text.TextUtils

object SkinResources {
    // app原始的resource
    private lateinit var mAppResources: Resources

    // 皮肤包的resource
    private var mSkinResources: Resources? = null
    private var mSkinPkgName: String? = null
    private var defaultSkin = true


    fun init(appResources: Resources, skinResources: Resources?, skinPkgName: String?) {
        mAppResources = appResources
        mSkinResources = skinResources
        mSkinPkgName = skinPkgName
        defaultSkin = TextUtils.isEmpty(skinPkgName) || (mSkinResources == null)
    }

    private fun getIdentifier(resId: Int): Int {
        if (defaultSkin) {
            return resId
        }
        val resName = mAppResources.getResourceEntryName(resId)
        val resType = mAppResources.getResourceTypeName(resId)
        // 获取皮肤包资源的id值
        return mSkinResources?.getIdentifier(resName, resType, mSkinPkgName) ?: 0
    }

    fun getColorStateList(resId: Int): ColorStateList? {
        if (defaultSkin) {
            return mAppResources.getColorStateList(resId)
        }
        val skinId = getIdentifier(resId)
        return if (skinId == 0) {
            mAppResources.getColorStateList(resId)
        } else {
            mSkinResources?.getColorStateList(skinId)
        }
    }

    fun getBackground(resId: Int): Any? {
        val resType = mAppResources.getResourceTypeName(resId)
        return if ("color" == resType) {
            getColor(resId)
        } else {
            getDrawable(resId)
        }
    }

    private fun getColor(resId: Int): Int {
        if (defaultSkin) {
            return mAppResources.getColor(resId)
        }
        val skinId: Int = getIdentifier(resId)
        return if (skinId == 0) {
            mAppResources.getColor(resId)
        } else mSkinResources?.getColor(skinId) ?: 0
    }

    private fun getDrawable(resId: Int): Drawable? {
        if (defaultSkin) {
            return mAppResources!!.getDrawable(resId)
        }
        //通过 app的resource 获取id 对应的 资源名 与 资源类型
        //找到 皮肤包 匹配 的 资源名资源类型 的 皮肤包的 资源 ID
        val skinId: Int = getIdentifier(resId)
        return if (skinId == 0) {
            mAppResources.getDrawable(resId)
        } else mSkinResources?.getDrawable(skinId)
    }
}